/**
 * @(#)DevicesManager.java 2016年11月4日
 * Copyright(C) 2016 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.service;


import java.math.BigDecimal;
import java.util.*;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.bto.AppInfo;
import org.jsbd.boss.bto.HttpResult;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.domian.DMClientInfo;
import org.jsbd.boss.domian.IpRange;
import org.jsbd.boss.domian.WifiInfo;
import org.jsbd.boss.domian.channel.MobileClient;
import org.jsbd.boss.domian.channel.ThirdUser;
import org.jsbd.boss.domian.channel.UserClientInfo;
import org.jsbd.boss.enums.*;
import org.jsbd.boss.mq.KafkaMqManager;
import org.jsbd.boss.service.impl.CacheParamManager;
import org.jsbd.boss.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.ReturnType;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.qy.recphone.service.IRecPhoneService;

import edu.hziee.cap.common.util.Md5Utils;
import edu.hziee.common.lang.StringUtil;
import edu.hziee.common.queue.DelayExecuteBuffer;

/**
 * 真实用户信息
 *
 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
 * @version 1.0.0
 */
@Service
public class ClientManager {
    public static final Logger LOGGER = LoggerFactory.getLogger(ClientManager.class);

    @Resource
    private RedisClient<String, Object> redisClient;

    @Resource
    private RedisClient redisClientTemp;

    @Resource
    private IWifiInfoService wifiInfoService;

    @Resource
    private CacheParamManager cacheParamManager;

    @Resource
    private IMobileClientService mobileClientService;
    @Resource
    private IRecPhoneService recPhoneService;

    @Resource
    private DelayExecuteBuffer<UserClientInfo> userClientBatchUpdateBuffer;


    @Resource
    private IApkSimulatorService apkSimulatorService;


    /**
     * updateFailTimesOfImsi:更新用户失败次数
     *
     * @param imsi
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public void updateFailTimesOfImsi(String imsi) {
        redisClientTemp.evalIncrby(CacheKey.I_F_TIMES + DateUtil.getDaysOfTime() + imsi, "1", String.valueOf(DateUtil.leftTimeToMidNight() / 1000));
    }

    /**
     * updateSuccTimesOfImsi:更新用户成功但是任务没有添加成功的次数
     *
     * @param imsi
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public void updateSuccTimesOfImsi(String imsi) {
        redisClientTemp.evalIncrby(CacheKey.I_S_TIMES + DateUtil.getDaysOfTime() + imsi, "1", String.valueOf(DateUtil.leftTimeToMidNight() / 1000));
    }

    /**
     * checkImsi:imsi校验
     * MCC中国表示460
     * MNC：00、02、04、07表示中国移动，03、05、11表示电信，01、06、09表示联通，中国铁通20
     *
     * @param imsi
     * @return
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public static Integer checkImsi(String imsi) {
        Integer carrier = -1;
        if (StringUtils.isNotBlank(imsi) && imsi.length() == 15) {
            String target = imsi.substring(0, 5);
            if ("46000,46002,46007,46004".contains(target)) {
                carrier = CarrierEnum.MOBILE.getType();
            } else if ("46001,46006,46009".contains(target)) {
                carrier = CarrierEnum.UNICOM.getType();
            } else if ("46003,46005,46011".contains(target)) {
                carrier = CarrierEnum.TELECOM.getType();
            }
        }
        return carrier;
    }


    public boolean isNewClient(String uuid) {
        String isExist = CacheKey.FILE_UPLOAD_FINISH_KEY + uuid;
        Object fileExists = redisClient.get(isExist);
        if (fileExists != null) {
            return true;
        }
        return false;
    }

    public boolean isNewSdkVersion(String sdkVer) {
        String targetVersion = (String) cacheParamManager.getParamValue(CacheKey.NEW_SDK_VERSION);
        if (targetVersion != null) {
            return VersonCompareUtil.compareVersion(sdkVer, targetVersion) >= 0;
        }
        return false;
    }


    /**
     * isUnusefulImsi:在指定时间内是否是无效用户
     *
     * @param imsi
     * @return
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public boolean isUnusefulImsi(String imsi) {
        if (isUnUseful(imsi, CacheKey.I_F_TIMES, CacheKey.I_F_TIME)) {
            // 统计丢失的用户数
            KafkaMqManager.lostImsiToQueue(imsi);
            return true;
        }
        if (isUnUseful(imsi, CacheKey.I_S_TIMES, CacheKey.I_S_TIME)) {
            // 统计丢失的用户数
            KafkaMqManager.lostImsiToQueue(imsi);
            return true;
        }
        return false;
    }

    /**
     * isUnUseful:用户失败或者成功次数
     *
     * @param imsi
     * @param timesKey
     * @param timeKey
     * @return
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public boolean isUnUseful(String imsi, String timesKey, String timeKey) {
        String key = timesKey + DateUtil.getDaysOfTime() + imsi;
        String execTimes = redisClientTemp.evalGet(key);
        Object times = cacheParamManager.getParamValue(timeKey);
        if (times != null && execTimes != null) {
            int defineTime = Integer.parseInt(times.toString());
            if (Integer.parseInt(execTimes) >= defineTime) {
                return true;
            }
        }
        return false;
    }

    public void recordSdkClient(DMClientInfo clientInfo) {
        redisClientTemp.put(CacheKey.CS_DAY + clientInfo.getImsi(), clientInfo, 1800);
    }


    public DMClientInfo getClientOfSdk(String imsi) {
        Object obj = redisClientTemp.get(CacheKey.CS_DAY + imsi);
        if (obj != null) {
            return (DMClientInfo) obj;
        } else {
            return null;
        }
    }

    /**
     * @param clientInfo
     */
    public void recordNoSdkClient(DMClientInfo clientInfo) {
        redisClientTemp.put(CacheKey.CS_DAY + clientInfo.getImsi() + "_1", clientInfo, 1800);
    }


    public DMClientInfo getNoSdkClientOfLogin(String imsi) {
        Object obj = redisClientTemp.get(CacheKey.CS_DAY + imsi + "_1");
        if (obj != null) {
            return (DMClientInfo) obj;
        } else {
            return null;
        }
    }

    private Integer setIntegerValue(String value) {
        try {
            if (StringUtils.isNotBlank(value)) {
                return Integer.parseInt(value);
            } else {
                return 0;
            }
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    private Double setDoubleValue(String value) {
        try {
            if (value != null) {
                return Double.parseDouble(value);
            } else {
                return 0d;
            }
        } catch (NumberFormatException e) {
            return 0d;
        }
    }

    private Short setShortValue(String value) {
        try {
            if (StringUtils.isNotBlank(value)) {
                return Short.parseShort(value);
            } else {
                return 0;
            }
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    private String valueOf(Object obj) {
        return (obj == null) ? null : obj.toString();
    }

    /**
     * initClientInfo:初始化客户端信息
     *
     * @param task
     * @return
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public DMClientInfo initClientInfo(String task) {
        Map clientMap = (Map) JSONObject.parse(task);
        DMClientInfo clientInfo = new DMClientInfo();
        clientInfo.setXdpi(setDoubleValue(valueOf(clientMap.get("xdpi"))));
        clientInfo.setSystime(valueOf(clientMap.get("systime")));
        clientInfo.setYdpi(setDoubleValue(valueOf(clientMap.get("ydpi"))));
        clientInfo.setDensityDpi(setDoubleValue(valueOf(clientMap.get("densityDpi"))));
        clientInfo.setProvince(setIntegerValue(valueOf(clientMap.get("province"))));
        clientInfo.setCity(setIntegerValue(valueOf(clientMap.get("cityid"))));
        clientInfo.setMark(valueOf(clientMap.get("mark")));
        clientInfo.setLac(setIntegerValue(valueOf(clientMap.get("lac"))));
        clientInfo.setCellId(setIntegerValue(valueOf(clientMap.get("cid"))));
        clientInfo.setLongitude(valueOf(clientMap.get("Longitude")));
        clientInfo.setLatitude(valueOf(clientMap.get("Latitude")));
        clientInfo.setHsman(valueOf(clientMap.get("ro.product.manufacturer")));
        clientInfo.setHstype(valueOf(clientMap.get("ro.product.model")));
        clientInfo.setScreenWidth(setShortValue(valueOf(clientMap.get("widthPixels"))));
        clientInfo.setScreenHeight(setShortValue(valueOf(clientMap.get("heightPixels"))));
        clientInfo.setCpu(valueOf(clientMap.get("cpuName")));
        clientInfo.setImsi(valueOf(clientMap.get("imsi")));
        clientInfo.setImei(valueOf(clientMap.get("imei")));
        clientInfo.setMac(valueOf(clientMap.get("mac")));
        clientInfo.setIccid(valueOf(clientMap.get("ICCID")));
        clientInfo.setSdId(valueOf(clientMap.get("sd_id")));
        clientInfo.setBuildVersion(valueOf(clientMap.get("ro.build.version.sdk")));
        clientInfo.setRelease(valueOf(clientMap.get("ro.build.version.release")));
        clientInfo.setSerialno(valueOf(clientMap.get("ro.serialno")));
        clientInfo.setPhoneType(valueOf(clientMap.get("phoneType")));
        clientInfo.setAndroidId(valueOf(clientMap.get("android_id")));
        clientInfo.setProductName(valueOf(clientMap.get("ro.product.name")));
        clientInfo.setProductDevice(valueOf(clientMap.get("ro.product.device")));
        clientInfo.setDensity(valueOf(clientMap.get("density")));
        String appInfo = valueOf(clientMap.get("appInfo"));
        if (StringUtils.isNotBlank(appInfo)) {
            AppInfo appinfo = JSONObject.parseObject(appInfo, AppInfo.class);
            clientInfo.setAppName(appinfo.getApp_name());
            clientInfo.setSystemAppName(appinfo.getSystem_app_name());
        }
        clientInfo.setUserAgent(valueOf(clientMap.get("userAgent")));
        clientInfo.setBoard(valueOf(clientMap.get("ro.product.board")));
        clientInfo.setCpuSerial(valueOf(clientMap.get("cpuSerial")));
        clientInfo.setKernelVer(valueOf(clientMap.get("kernelVer")));
        clientInfo.setNetworkExtraInfo(valueOf(clientMap.get("networkExtraInfo")));
        clientInfo.setNetworkOperator(valueOf(clientMap.get("networkOperator")));
        clientInfo.setNetworkOperatorName(valueOf(clientMap.get("networkOperatorName")));
        clientInfo.setSimOperatorName(valueOf(clientMap.get("simOperator")));
        clientInfo.setWifiInfo(valueOf(clientMap.get("wifiInfo")));
        clientInfo.setLoginType(setIntegerValue(valueOf(clientMap.get("loginType"))));
        clientInfo.setNetworkType(setIntegerValue(valueOf(clientMap.get("networkType"))));
        clientInfo.setBuildId(valueOf(clientMap.get("ro.build.id")));
        clientInfo.setSdkUuid(valueOf(clientMap.get("sdkUuid")));
        clientInfo.setSensorInfo(valueOf(clientMap.get("sensorInfo")));
        clientInfo.setPayMax(setDoubleValue(valueOf(clientMap.get("payMax"))));
        clientInfo.setPayMin(setDoubleValue(valueOf(clientMap.get("payMin"))));
        clientInfo.setPayRate(setDoubleValue(valueOf(clientMap.get("payRate"))));
        clientInfo.setApkId(setIntegerValue(valueOf(clientMap.get("apkId"))));
        clientInfo.setBase(setIntegerValue(valueOf(clientMap.get("base"))));
        clientInfo.setScript(valueOf(clientMap.get("scriptPath")));
        clientInfo.setBrushId(setIntegerValue(valueOf(clientMap.get("brushId"))));
        return clientInfo;
    }

    /**
     * initClientInfo:initClientInfo:初始化客户端信息
     *
     * @param httpResult
     * @param ipRange
     * @return
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public DMClientInfo initClientInfo(HttpResult httpResult, IpRange ipRange) {
        DMClientInfo clientInfo = new DMClientInfo();
        clientInfo.setDensityDpi(httpResult.getDensityDpi());
        clientInfo.setSystime(String.valueOf(System.currentTimeMillis()));
        clientInfo.setProvince(ipRange.getProvinceId());
        clientInfo.setCity(ipRange.getCityId());
        clientInfo.setIp(httpResult.getIp());
        clientInfo.setBuildId(httpResult.getBuildId());
        if (!StringUtil.isBlank(httpResult.getLac())) {
            clientInfo.setLac(Integer.parseInt(httpResult.getLac()));
        }
        if (!StringUtil.isBlank(httpResult.getCellId())) {
            clientInfo.setCellId(Integer.parseInt(httpResult.getCellId()));
        }
        clientInfo.setLongitude(httpResult.getLongitude());
        clientInfo.setLatitude(httpResult.getLatitude());
        clientInfo.setSmsCenter(httpResult.getSmsCenter());
        clientInfo.setChannelId(httpResult.getChannelId());
        clientInfo.setAppId(httpResult.getAppId());
        if (!StringUtil.isBlank(httpResult.getSdkVerCode())) {
            clientInfo.setSdkVerCode(Integer.parseInt(httpResult.getSdkVerCode()));
        }
        clientInfo.setSdkVerName(httpResult.getSdkVerName());
        if (!StringUtil.isBlank(httpResult.getClientVerCode())) {
            clientInfo.setClientVerCode(Integer.parseInt(httpResult.getClientVerCode()));
        }
        clientInfo.setClientVerName(httpResult.getClientVerName());
        clientInfo.setHsman(httpResult.getHsman());
        clientInfo.setHstype(httpResult.getHstype());
        clientInfo.setOsVer(httpResult.getOsVer());
        short width = 0, height = 0;
        String screenWidth = httpResult.getScreenWidth();
        String screenHeight = httpResult.getScreenHeight();
        if (!StringUtil.isBlank(screenWidth)) {
            width = Short.parseShort(screenWidth);
        }
        if (!StringUtil.isBlank(screenHeight)) {
            height = Short.parseShort(screenHeight);
        }
        double xdpi = 0, ydpi = 0;
        Double xdpi1 = httpResult.getXdpi();
        Double ydpi1 = httpResult.getYdpi();
        if (xdpi1 != null) {
            xdpi = xdpi1;
        }
        if (ydpi1 != null) {
            ydpi = ydpi1;
        }
        BigDecimal y = new BigDecimal(ydpi);
        ydpi = y.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

        BigDecimal x = new BigDecimal(xdpi);
        xdpi = x.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

        if (width > height) {
            clientInfo.setScreenWidth(height);
            clientInfo.setScreenHeight(width);
            clientInfo.setXdpi(ydpi);
            clientInfo.setYdpi(xdpi);
        } else {
            clientInfo.setScreenWidth(width);
            clientInfo.setScreenHeight(height);
            clientInfo.setXdpi(xdpi);
            clientInfo.setYdpi(ydpi);
        }
        clientInfo.setCpu(httpResult.getCpu());
        if (!StringUtil.isBlank(httpResult.getRamSize())) {
            clientInfo.setRamSize(Integer.parseInt(httpResult.getRamSize()));
        }
        if (!StringUtil.isBlank(httpResult.getRomSize())) {
            clientInfo.setRomSize(Integer.parseInt(httpResult.getRomSize()));
        }
        if (!StringUtil.isBlank(httpResult.getExtraSize())) {
            clientInfo.setExtraSize(Integer.parseInt(httpResult.getExtraSize()));
        }

        if (!StringUtil.isBlank(httpResult.getNetworkType())) {
            clientInfo.setNetworkType(Integer.parseInt(httpResult.getNetworkType()));
        }
        //这个在外层判断了
//        String imei = httpResult.getImei();
//        if (!isRightImei(imei)) {
//            return null;
//        }
        clientInfo.setImsi(httpResult.getImsi());
        clientInfo.setImei(httpResult.getImei());
        clientInfo.setPhoneNum(httpResult.getPhoneNum());
        clientInfo.setMac(httpResult.getMac());
        clientInfo.setIccid(httpResult.getICCID());
        clientInfo.setSdId(httpResult.getSd_id());
        if (!StringUtil.isBlank(httpResult.getRoot())) {
            clientInfo.setRoot(Integer.parseInt(httpResult.getRoot()));
        }
        if (!StringUtil.isBlank(httpResult.getNetworkSystem())) {
            clientInfo.setNetworkSystem(Integer.parseInt(httpResult.getNetworkSystem()));
        }
        if (!StringUtil.isBlank(httpResult.getBuild_version())) {
            clientInfo.setBuildVersion(httpResult.getBuild_version());
        }

        if (!StringUtil.isBlank(httpResult.getOsVer())) {
            String[] osVers = httpResult.getOsVer().split("_");
            if (osVers.length == 1) {
                clientInfo.setRelease(osVers[0]);
            } else {
                clientInfo.setRelease(osVers[1]);
            }
        }
        clientInfo.setSerialno(httpResult.getSerialno());
        clientInfo.setPhoneType(httpResult.getNetworkSystem() + "");
        clientInfo.setAndroidId(httpResult.getAndroidId());
        clientInfo.setProductName(httpResult.getProductName());
        clientInfo.setProductDevice(httpResult.getProductDevice());
        clientInfo.setDensity(httpResult.getDensity());

        AppInfo appInfo = initClientAppName(httpResult.getAppInfo(), clientInfo.getHsman(), clientInfo.getHstype());
        clientInfo.setAppName(appInfo.getApp_name());
        clientInfo.setSystemAppName(appInfo.getSystem_app_name());
        clientInfo.setUserAgent(httpResult.getUserAgent());
        clientInfo.setBoard(httpResult.getBoard());
        clientInfo.setCpuSerial(httpResult.getCpuSerial());
        clientInfo.setKernelVer(httpResult.getKernelVersion());
        clientInfo.setNetworkExtraInfo(httpResult.getNetworkExtraInfo());
        clientInfo.setNetworkOperator(httpResult.getNetworkOperator());
        clientInfo.setNetworkOperatorName(httpResult.getNetworkOperatorName());
        clientInfo.setSimOperatorName(httpResult.getSimOperatorName());
        // 判断wifi信息是否为空，如果为空，则从数据库中获取wifi信息，否则直接用客户端的wifi信息
        if (StringUtils.isBlank(httpResult.getReserved3())) {
            // 根据手机号码区域段，获取用户地理信息
            WifiInfo wifiInfo = new WifiInfo();
            wifiInfo.setIpCity(ipRange.getCityId());
            wifiInfo.setIpProvince(ipRange.getProvinceId());
            wifiInfo = wifiInfoService.findRandomWifiInfo(wifiInfo);
            if (wifiInfo == null) {
                LOGGER.warn("imsi cannot get wifi {}", clientInfo.getImsi());
                return null;
            } else {
                clientInfo.setWifiInfo(wifiInfo.getWifiInfo());
            }
        } else {
            clientInfo.setWifiInfo(httpResult.getReserved3());
        }
        String wifiInfo = clientInfo.getWifiInfo();
        // 判断getWifiInfo不要超过数据库字段长度
        if (StringUtils.isNotBlank(wifiInfo) && wifiInfo.length() > 1000) {
            wifiInfo = wifiInfo.substring(0, 1000);
            clientInfo.setWifiInfo(wifiInfo.substring(0, wifiInfo.lastIndexOf("|")));
        }
        httpResult.setReserved3(clientInfo.getWifiInfo());
        clientInfo.setSdkUuid(httpResult.getUuid());
        clientInfo.setSensorInfo(httpResult.getSensorInfo());
        return clientInfo;
    }

    public AppInfo initClientAppName(String appInfoStr, String hsman, String hstype) {
        AppInfo appInfo = new AppInfo();
        if (StringUtils.isNotBlank(appInfoStr)) {
            appInfo = JSONObject.parseObject(appInfoStr, AppInfo.class);
            String sysAppName = appInfo.getSystem_app_name();
            String appName = getAppName(appInfo);
            if (StringUtils.isBlank(appName)) {
                appInfo.setApp_name(AppNameUtil.getAppName());
            } else {
                appInfo.setApp_name(appName);
            }
            if (StringUtils.isBlank(sysAppName)) {
                MobileClient mobileClient = mobileClientService.selectMobileClient(hstype, hsman);
                if (mobileClient != null) {
                    sysAppName = mobileClient.getSystemAppName();
                    appInfo.setSystem_app_name(sysAppName);
                }
            }
        } else {
            appInfo.setApp_name(AppNameUtil.getAppName());
            MobileClient mobileClient = mobileClientService.selectMobileClient(hstype, hsman);
            if (mobileClient != null) {
                String sysAppName = mobileClient.getSystemAppName();
                appInfo.setSystem_app_name(sysAppName);
            }
        }
        return appInfo;
    }

    private String getAppName(AppInfo appInfo) {
        String appName = appInfo.getApp_name();
        if (StringUtils.isNotBlank(appName)) {
            return appName;
        }
        appName = appInfo.getAppName();
        if (StringUtils.isNotBlank(appName)) {
            return appName;
        }
        return null;
    }


    /**
     * @param imsi
     * @param apkId
     * @param base
     * @return
     */
    public boolean hasLogined(String imsi, Integer apkId, Integer base) {
        Set<Integer> hasDoApks = getImsiHasDoApks(imsi);
        if (hasDoApks.contains(apkId) || hasDoApks.contains(base)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * login:用户登录
     *
     * @param imsi
     * @param apkId
     * @param base
     * @param time
     * @return
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public boolean login(String imsi, Integer apkId, Integer base, long time) {
        String key = CacheKey.A_IMSI + imsi;
        String hasLoginKey = null;
        if (base == null || base == ApkBaseEnum.OTHER.getType()) {// 和基地无关
            if (apkId == null) {
                return false;
            }
            hasLoginKey = apkId + "|" + time + "|";
        } else {// 和基地有关
            hasLoginKey = base + "|" + time + "|";
        }
        return (boolean) redisClient.eval("return redis.call('append', KEYS[1],KEYS[2])", ReturnType.BOOLEAN, new String[]{key, hasLoginKey});
    }

    /**
     * getImsiHasDoApks:imsi已经做过的apk记录
     *
     * @param imsi
     * @return
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public Set<Integer> getImsiHasDoApks(String imsi) {
        Set<Integer> hasDoApks = new HashSet<Integer>();
        String key = CacheKey.A_IMSI + imsi;
        String obj = redisClient.evalGet(key);
        if (obj != null) {
            long now = System.currentTimeMillis();
            long expire = 15552000000L;
            Object expireTime = cacheParamManager.getParamValue(CacheKey.IMSI_CACHE_TIME);
            if (expireTime != null) {
                expire = Long.parseLong(expireTime.toString());
            }
            StringTokenizer tokenizer = new StringTokenizer(obj, "\\|", false);
            while (tokenizer.hasMoreElements()) {
                try {
                    String baseOrapk = (String) tokenizer.nextElement();
                    // 任务做的时间记录 有在半年内的就做过
                    long earlierTimer = Long.parseLong((String) tokenizer.nextElement());
                    //2018-09-07 18:18:00 到 2018-09-08 21:58:00 的记录作废 2018-09-11 add
                    if (earlierTimer >= 1536315480000L && earlierTimer <= 1536415080000L && !HasDoUtil.contain(imsi)) {
                        continue;
                    }

                    long hasPassTime = now - earlierTimer;
                    if (expire >= hasPassTime) {
                        hasDoApks.add(Integer.parseInt(baseOrapk));
                    }
                } catch (Exception e) {
                    LOGGER.warn("已做imsi参数错误 : {}", imsi);
                }
            }
        }
        return hasDoApks;
    }


    /**
     * hasReserveDoApk:是否预留
     *
     * @param imsi
     * @param apkId
     * @param base
     * @return
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public boolean hasReserveDoApk(String imsi, Integer apkId, Integer base) {
        String key = CacheKey.A_R_IMSI + imsi;
        Integer apkOrBase = 0;
        if (base == ApkBaseEnum.OTHER.getType()) {
            apkOrBase = apkId;
        } else {
            apkOrBase = base;
        }
        long now = System.currentTimeMillis();
        long expire = 15552000000L;
        Object expireTime = cacheParamManager.getParamValue(CacheKey.IMSI_CACHE_TIME);
        if (expireTime != null) {
            expire = Long.parseLong(expireTime.toString());
        }
        Object earlierTime = redisClient.getHash(key, apkOrBase.toString());
        if (earlierTime != null) {
            long earlierTimes = Long.parseLong(earlierTime.toString());
            long hasPassTime = now - earlierTimes;
            if (expire >= hasPassTime) {
                return true;
            }
        }
        return false;
    }

    /**
     * addReserveDoApk:记录预留imsi记录
     *
     * @param imsi
     * @param apkId
     * @param base
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public void addReserveDoApk(String imsi, Integer apkId, Integer base) {
        String key = CacheKey.A_R_IMSI + imsi;
        Integer apkOrBase = 0;
        if (base == ApkBaseEnum.OTHER.getType()) {
            apkOrBase = apkId;
        } else {
            apkOrBase = base;
        }
        redisClient.putHash(key, apkOrBase.toString(), System.currentTimeMillis());
    }

    /**
     * addImsiSmsCode:记录用户的发送短信验证码
     *
     * @param imsi
     * @param apk
     * @param smsCode
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public void recordImsiSmsCode(String imsi, String apk, String smsCode) {
        String sdkVersion = (String) cacheParamManager.getParamValue(CacheKey.NEW_SIMULATOR_VERSION);
        if (sdkVersion != null) {
            String sysVer = apkSimulatorService.getVer(apk);
            if (sysVer != null && VersonCompareUtil.compareSimulatorVersion(sysVer, sdkVersion) >= 0 && redisClient.evalSetNx(CacheKey.NEW_SMS_LOCK + ":" + imsi + apk + smsCode, 900)) {
                String queueKey = CacheKey.NEW_SMS_QUEUE;
                Map<String, String> map = new HashMap<>();
                map.put("imsi", imsi);
                map.put("mark", apk);
                map.put("smsCode", smsCode);
                redisClient.evalLpush(queueKey, JSONObject.toJSONString(map));
            }
        }
        redisClient.put(CacheKey.I_A_SMSCODE + imsi + apk, smsCode, 900);
    }

    /**
     * getImsiSmsCode:获取短信验证码
     *
     * @param imsi
     * @param apk
     * @return
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public String getImsiSmsCode(String imsi, String apk) {
        return (String) redisClient.get(CacheKey.I_A_SMSCODE + imsi + apk);
    }


    /**
     * checkClient:客户端数据校验
     *
     * @param client
     * @return
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public DataCheckStatusEnum checkClient(UserClientInfo client) {
        DataCheckStatusEnum status = DataCheckStatusEnum.SUCCESS;
        try {
            String hstype = client.getHstype();
            String hsman = client.getHsman();
            if (StringUtils.isBlank(hstype) || StringUtils.isBlank(hsman) || StringUtils.isBlank(client.getImsi())) {
                LOGGER.warn("hstype[{}] or hsman[{}] or imsi[{}] ", new Object[]{hstype, hsman, client.getImsi(), client.getProvince(), client.getLac()});
                return DataCheckStatusEnum.FAIL;
            }
            MobileClient mobileClient = mobileClientService.selectMobileClient(hstype, hsman);
            //长度15-17为
            if (!isRightImei(client.getImei())) {
                String imei = initImei(client.getImsi());
                if (StringUtils.isNotBlank(imei)) {
                    client.setImei(imei);
                    status = DataCheckStatusEnum.UPDATE;
                } else {
                    LOGGER.warn("imei is emtpy ,imsi [{}]", client.getImsi());
                    return DataCheckStatusEnum.FAIL;
                }
            }
            Integer city = client.getCity();
            if (city == null) {
                client.setCity(-1);
            }
            String cpuSerial = client.getCpuSerial();
            if (StringUtils.isBlank(cpuSerial)) {
                if (mobileClient != null && StringUtils.isNotBlank(mobileClient.getCpuSerial())) {
                    client.setCpuSerial(mobileClient.getCpuSerial());
                } else {
                    client.setCpuSerial("0000000000000000");
                }
                status = DataCheckStatusEnum.UPDATE;
            }
            // 必填
            String iccid = client.getIccid();
            if (StringUtils.isBlank(iccid)) {
                iccid = initIccid(client.getImsi(), client.getPhoneNum(), client.getProvince());
                if (StringUtils.isNotBlank(iccid)) {
                    client.setIccid(iccid);
                    status = DataCheckStatusEnum.UPDATE;
                } else {
                    LOGGER.warn("geticcid is emtpy ,imsi [{}]", client.getImsi());
                    return DataCheckStatusEnum.FAIL;
                }
            }
            // 必填
            if (StringUtils.isBlank(client.getKernelVer())) {
                if (mobileClient == null || StringUtils.isBlank(mobileClient.getKernelVer())) {
                    LOGGER.warn("KernelVer is emtpy ,imsi [{}]", client.getImsi());
                    return DataCheckStatusEnum.FAIL;
                }
                client.setKernelVer(mobileClient.getKernelVer());
                status = DataCheckStatusEnum.UPDATE;
            }
            // 必填
            if (StringUtils.isBlank(client.getSerialno())) {
                String serialNo = initSerialNo(client.getImsi());
                if (StringUtils.isNotBlank(serialNo)) {
                    client.setSerialno(serialNo);
                    status = DataCheckStatusEnum.UPDATE;
                } else {
                    return DataCheckStatusEnum.FAIL;
                }
            }

            // 必填
            if (StringUtils.isBlank(client.getWifiInfo())) {
                WifiInfo wifiInfo = new WifiInfo();
                wifiInfo.setIpCity(client.getCity());
                wifiInfo.setIpProvince(client.getProvince());
                wifiInfo = wifiInfoService.findRandomWifiInfo(wifiInfo);
                int i = 0;
                while (i < 3) {
                    if (wifiInfo != null) {
                        client.setWifiInfo(wifiInfo.getWifiInfo());
                        status = DataCheckStatusEnum.UPDATE;
                        break;
                    } else {
                        wifiInfo = wifiInfoService.findRandomWifiInfo(wifiInfo);
                    }
                    i++;
                }
                if (StringUtils.isBlank(client.getWifiInfo())) {
                    LOGGER.warn("wifiInfo is emtpy ,imsi [{}]", client.getImsi());
                    return DataCheckStatusEnum.FAIL;
                }

            }

            if (StringUtils.isBlank(client.getPhoneType())) {
                client.setPhoneType("1");
                status = DataCheckStatusEnum.UPDATE;
            }

            if (client.getNetworkType() == null) {
                client.setNetworkType(NetworkTypeEnum.WIFI.getType());
                status = DataCheckStatusEnum.UPDATE;
            }

            if (StringUtils.isBlank(client.getNetworkExtraInfo())) {
                client.setNetworkExtraInfo(WifiUtil.getWifiName());
                status = DataCheckStatusEnum.UPDATE;
            }
            // 必填
            if (StringUtils.isBlank(client.getProductDevice())) {
                if (mobileClient == null || StringUtils.isBlank(mobileClient.getProductDevice())) {
                    LOGGER.warn("ProductDevice is emtpy ,imsi [{}]", client.getImsi());
                    return DataCheckStatusEnum.FAIL;
                }
                client.setProductDevice(mobileClient.getProductDevice());
                status = DataCheckStatusEnum.UPDATE;
            }
            // 必填
            if (StringUtils.isBlank(client.getProductName())) {
                if (mobileClient == null || StringUtils.isBlank(mobileClient.getProductName())) {
                    LOGGER.warn("ProductName is emtpy ,imsi [{}]", client.getImsi());
                    return DataCheckStatusEnum.FAIL;
                }
                client.setProductName(mobileClient.getProductName());
                status = DataCheckStatusEnum.UPDATE;
            }
            // 必填
            if (StringUtils.isBlank(client.getDensity())) {
                if (mobileClient == null || StringUtils.isBlank(mobileClient.getDensity())) {
                    LOGGER.warn("Density is emtpy ,imsi [{}]", client.getImsi());
                    return DataCheckStatusEnum.FAIL;
                }
                client.setDensity(mobileClient.getDensity());
                status = DataCheckStatusEnum.UPDATE;

            }
            if (client.getDensityDpi() == null) {
                if (mobileClient != null && mobileClient.getDensityDpi() != null) {
                    client.setDensityDpi(mobileClient.getDensityDpi());
                    status = DataCheckStatusEnum.UPDATE;
                }
            }

            // 必填
            if (StringUtils.isBlank(client.getSdId())) {
                client.setSdId(Md5Utils.getMd5(client.getImsi()));
                status = DataCheckStatusEnum.UPDATE;
            }

            // 必填
            if (StringUtils.isBlank(client.getMac())) {
                String mac = initMac(client.getImsi());
                if (mac != null) {
                    client.setMac(mac);
                    status = DataCheckStatusEnum.UPDATE;
                } else {
                    LOGGER.warn("mac is emtpy ,imsi [{}]", client.getImsi());
                    return DataCheckStatusEnum.FAIL;
                }
            }

            // 必填
            if (StringUtils.isBlank(client.getAndroidId())) {
                String androidId = initAndriodId(client.getImsi());
                if (androidId != null) {
                    client.setAndroidId(androidId);
                    status = DataCheckStatusEnum.UPDATE;
                } else {
                    LOGGER.warn("andriodId is emtpy ,imsi [{}]", client.getImsi());
                    return DataCheckStatusEnum.FAIL;
                }
            }

            // 必填
            if (StringUtils.isBlank(client.getRelease())) {
                if (mobileClient == null || StringUtils.isBlank(mobileClient.getRelease())) {
                    LOGGER.warn("Release is emtpy ,imsi [{}]", client.getImsi());
                    return DataCheckStatusEnum.FAIL;
                }
                client.setRelease(mobileClient.getRelease());
                status = DataCheckStatusEnum.UPDATE;
            }
            // 必填
            if (StringUtils.isBlank(client.getBuildVersion())) {
                if (mobileClient == null || StringUtils.isBlank(mobileClient.getBuildVersion())) {
                    LOGGER.warn("BuildVersion is emtpy ,hstype {} hsman {}", hstype, hsman);
                    return DataCheckStatusEnum.FAIL;
                } else {
                    client.setBuildVersion(mobileClient.getBuildVersion());
                    status = DataCheckStatusEnum.UPDATE;
                }
            }

            if (StringUtils.isBlank(client.getUserAgent())) {
                if (mobileClient != null && StringUtils.isNotBlank(mobileClient.getUserAgent())) {
                    client.setUserAgent(mobileClient.getUserAgent());
                    status = DataCheckStatusEnum.UPDATE;
                }
            }

            if (StringUtils.isBlank(client.getCpu())) {
                if (mobileClient != null && StringUtils.isNotBlank(mobileClient.getCpu())) {
                    client.setCpu(mobileClient.getCpu());
                    status = DataCheckStatusEnum.UPDATE;
                }
            }

            if (client.getXdpi() == null) {
                if (mobileClient != null && mobileClient.getXdpi() != null) {
                    client.setXdpi(mobileClient.getXdpi());
                    status = DataCheckStatusEnum.UPDATE;
                }
            }
            if (client.getYdpi() == null) {
                if (mobileClient != null && mobileClient.getYdpi() != null) {
                    client.setYdpi(mobileClient.getYdpi());
                    status = DataCheckStatusEnum.UPDATE;
                }
            }
            if (StringUtils.isBlank(client.getBoard())) {
                if (mobileClient != null && StringUtils.isNotBlank(mobileClient.getBoard())) {
                    client.setBoard(mobileClient.getBoard());
                    status = DataCheckStatusEnum.UPDATE;
                }
            }

            Short screenWidth = client.getScreenWidth();
            Short screenHeight = client.getScreenHeight();
            double xdpi = 0, ydpi = 0;
            Double xdpi1 = client.getXdpi();
            Double ydpi1 = client.getYdpi();
            if (xdpi1 != null) {
                xdpi = xdpi1;
            }
            if (ydpi1 != null) {
                ydpi = ydpi1;
            }

            BigDecimal y = new BigDecimal(ydpi);
            ydpi = y.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

            BigDecimal x = new BigDecimal(xdpi);
            xdpi = x.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            if (screenWidth != null && screenHeight != null && screenWidth > screenHeight) {
                client.setScreenWidth(screenHeight);
                client.setScreenHeight(screenWidth);
                client.setXdpi(ydpi);
                client.setYdpi(xdpi);
            } else {
                client.setScreenWidth(screenWidth);
                client.setScreenHeight(screenHeight);
                client.setXdpi(xdpi);
                client.setYdpi(ydpi);
            }
            Integer carrier = checkImsi(client.getImsi());
            if (carrier != null && carrier != -1) {
                client.setCarrier(carrier);
                if (status == DataCheckStatusEnum.UPDATE) {
                    userClientBatchUpdateBuffer.add(client);
                }
            } else {
                status = DataCheckStatusEnum.FAIL;
            }
        } catch (Exception e) {
            LOGGER.error("client {} checkClient error", client.getImsi(), e);
            status = DataCheckStatusEnum.FAIL;
        }
        return status;
    }

    /**
     * initAndriodId:初始化AndriodId
     *
     * @param imsi
     * @return
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public String initAndriodId(String imsi) {
        int i = 0;
        String key = CacheKey.HAS_ANDROIDID;
        while (i < 3) {
            Object hasAndroidId = redisClient.getHash(key, imsi);
            if (hasAndroidId == null) {
                String androidId = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
                Object hasImsi = redisClient.getHash(key, androidId);
                if (hasImsi == null) {
                    redisClient.putHash(key, androidId, imsi);
                    redisClient.putHash(key, imsi, androidId);
                    return androidId;
                }
            } else {
                return hasAndroidId.toString();
            }
            i++;
        }
        return null;
    }

    /**
     * initMac:获取mac
     *
     * @param imsi
     * @return
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public String initMac(String imsi) {
        int i = 0;
        String key = CacheKey.HAS_MAC;
        while (i < 3) {
            Object hasMac = redisClient.getHash(key, imsi);
            if (hasMac == null) {
                String mac = MacUtil.getMacAddrWithFormat(":");
                Object hasImsi = redisClient.getHash(key, mac);
                if (hasImsi == null) {
                    redisClient.putHash(key, mac, imsi);
                    redisClient.putHash(key, imsi, mac);
                    return mac;
                }
            } else {
                return hasMac.toString();
            }
            i++;
        }
        return null;

    }

    public String initSerialNo(String imsi) {
        int i = 0;
        String key = CacheKey.HAS_SERIALNO;
        while (i < 3) {
            Object hasSerialno = redisClient.getHash(key, imsi);
            if (hasSerialno == null) {
                String serialno = SerialNoUtil.getSerialNo();
                Object hasImsi = redisClient.getHash(key, serialno);
                if (hasImsi == null) {
                    redisClient.putHash(key, serialno, imsi);
                    redisClient.putHash(key, imsi, serialno);
                    return serialno;
                }
            } else {
                return hasSerialno.toString();
            }
            i++;
        }
        return null;
    }

    public String initImei(String imsi) {
        int i = 0;
        String key = CacheKey.HAS_IMEI;
        Object hasImei = redisClient.getHash(key, imsi);
        while (i < 3) {
            if (hasImei == null) {
                String imei = TermUtil.randomImei();
                Object hasImsi = redisClient.getHash(key, imei);
                if (hasImsi == null) {
                    redisClient.putHash(key, imei, imsi);
                    redisClient.putHash(key, imsi, imei);
                    return imei;
                }
            } else {
                return hasImei.toString();
            }
            i++;
        }
        return TermUtil.randomImei();
    }

    public String initImei(String imsi, String imei) {
        int i = 0;
        String key = CacheKey.HAS_IMEI;
        Object hasImei = redisClient.getHash(key, imsi);
        Object hasImsi = redisClient.getHash(key, imei);
        if (hasImei != null) {
            if (!isRightImei(hasImei.toString())) {
                hasImei = null;
            } else {
                if (!imsi.equals(hasImsi)) {
                    hasImsi = null;
                } else {
                    return imei;
                }
            }
        }
        if (hasImsi == null) {
            redisClient.putHash(key, imei, imsi);
            redisClient.putHash(key, imsi, imei);
            return imei;
        }
        while (i < 3) {
            if (hasImei == null) {
                String tempImei = TermUtil.randomImei();
                hasImsi = redisClient.getHash(key, tempImei);
                if (hasImsi == null) {
                    redisClient.putHash(key, tempImei, imsi);
                    redisClient.putHash(key, imsi, tempImei);
                    return tempImei;
                }
            } else {
                return hasImei.toString();
            }
            i++;
        }
        return TermUtil.randomImei();

    }

    private String getPhoneNum(String imsi) {
        String phoneNum = PhoneUtil.getMobileByIMSI(imsi);
        if (StringUtils.isNotBlank(phoneNum)) {
            phoneNum = phoneNum + (int) (Math.random() * 9000 + 1000);
            LOGGER.info("imsi {} phone {}", imsi, phoneNum);
            return phoneNum;
        } else {
            return null;
        }
    }

    public String initIccid(String imsi, String mobile, int provinceId) {
        if (StringUtils.isBlank(mobile)) {
            mobile = recPhoneService.getPhoneByImsi(imsi);
            if (StringUtils.isBlank(mobile)) {
                mobile = getPhoneNum(imsi);
            }
        }
        if (StringUtils.isBlank(mobile)) {
            return null;
        }
        String key = CacheKey.HAS_ICCID;
        int i = 0;
        while (i < 3) {
            Object hasIccid = redisClient.getHash(key, imsi);
            if (hasIccid == null) {
                String iccid = IccIDUtils.getYdIccId(provinceId, mobile);
                if (StringUtils.isNotBlank(iccid)) {
                    Object hasImsi = redisClient.getHash(key, iccid);
                    if (hasImsi == null) {
                        redisClient.putHash(key, iccid, imsi);
                        redisClient.putHash(key, imsi, iccid);
                        return iccid;
                    }
                }
            } else {
                return hasIccid.toString();
            }
            i++;
        }
        return null;
    }

    public boolean isRightImei(String imei) {
        if (StringUtils.isNotBlank(imei) && (imei.length() >= 15 && imei.length() <= 17)) {
            return true;
        }
//        LOGGER.error("imei 错误 {} {}", imsi, imei);
        return false;
    }

    /**
     * checkAndGetImsiAndImei:校验imsi和imei对应关系，imsi和imei唯一对应,如果获取到的imei不为空，
     * 历史的和缓存的对不上就重新生成 说明需要使用新的imei
     *
     * @param imsi
     * @param imei
     * @return
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public String checkAndGetImsiAndImei(String imsi, String imei) {
        String key = CacheKey.HAS_IMEI;
        Object hasImei = null;
        boolean isRight = isRightImei(imei);
        if (!isRight) {
            hasImei = redisClient.getHash(key, imsi);
            if (hasImei != null) {
                isRight = isRightImei(hasImei.toString());
                if (isRight) {
                    redisClient.putHash(key, hasImei.toString(), imsi);
                    return hasImei.toString();
                } else {
                    return initImei(imsi);
                }
            } else {
                return initImei(imsi);
            }
        } else {
            return initImei(imsi, imei);
        }
    }

    /**
     * checkOnlineAndGetImsiAndImei:在线的以线上的为准
     *
     * @param imsi
     * @param imei
     * @return
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public String checkOnlineAndGetImsiAndImei(String imsi, String imei) {
        String key = CacheKey.HAS_IMEI;
        boolean isRight = isRightImei(imei);
        if (!isRight) {
            Object hasImei = redisClient.getHash(key, imsi);
            if (hasImei != null) {
                isRight = isRightImei(hasImei.toString());
                if (isRight) {
                    redisClient.putHash(key, hasImei.toString(), imsi);
                    return hasImei.toString();
                } else {
                    return initImei(imsi);
                }
            } else {
                return initImei(imsi);
            }
        } else {
            redisClient.putHash(key, imei, imsi);
            redisClient.putHash(key, imsi, imei);
            return imei;
        }
    }

    /**
     * checkClient:校验客户端信息
     *
     * @param client
     * @return
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    public boolean checkClient(ThirdUser client) {
        String hstype = client.getHstype();
        String hsman = client.getHsman();
        String imsi = client.getImsi();
        String imei = client.getImei();
        StringBuffer sb = new StringBuffer();
        if (StringUtils.isBlank(hstype) || StringUtils.isBlank(hsman) || StringUtils.isBlank(imsi)) {
            LOGGER.warn("hstype[{}] or hsman[{}] or imsi[{}]", new Object[]{hstype, hsman, imsi});
            return false;
        }
        MobileClient mobileClient = mobileClientService.selectMobileClient(hstype, hsman);
        if (!isRightImei(client.getImei())) {
            imei = initImei(imsi);
            if (StringUtils.isBlank(imei)) {
                return false;
            } else {
                client.setImei(imei);
            }
            sb.append("imei,");
        }

        Integer city = client.getCity();

        if (city == null) {
            client.setCity(-1);
        }

        // 必填
        String iccid = client.getIccid();
        if (StringUtils.isBlank(iccid)) {
            iccid = initIccid(imsi, client.getPhoneNum(), client.getProvince());
            if (StringUtils.isNotBlank(iccid)) {
                client.setIccid(iccid);
                sb.append("iccid,");
            } else {
                LOGGER.warn("geticcid is emtpy ,imsi [{}]", imsi);
                return false;
            }
        }
        String cpuSerial = client.getCpuSerial();
        if (StringUtils.isBlank(cpuSerial) && (mobileClient == null || StringUtils.isBlank(mobileClient.getCpuSerial()))) {
            client.setCpuSerial("0000000000000000");
            sb.append("cpuSerial,");
        }
        // 必填
        if (StringUtils.isBlank(client.getKernelVer())) {
            if (mobileClient == null || StringUtils.isBlank(mobileClient.getKernelVer())) {
                LOGGER.warn("KernelVer is emtpy ,imsi [{}]", imsi);
                return false;
            }
            client.setKernelVer(mobileClient.getKernelVer());
        }
        // 必填
        if (StringUtils.isBlank(client.getSerialno())) {
            String serialNo = initSerialNo(imsi);
            if (StringUtils.isNotBlank(serialNo)) {
                client.setSerialno(serialNo);
            } else {
                LOGGER.warn("serialNo is emtpy ,imsi [{}]", imsi);
                return false;
            }
            sb.append("serialno,");
        }

        // 必填
        if (StringUtils.isBlank(client.getWifiInfo())) {
            WifiInfo wifiInfo = new WifiInfo();
            wifiInfo.setIpCity(client.getCity());
            wifiInfo.setIpProvince(client.getProvince());
            wifiInfo = wifiInfoService.findRandomWifiInfo(wifiInfo);
            int i = 0;
            while (i < 3) {
                if (wifiInfo != null) {
                    client.setWifiInfo(wifiInfo.getWifiInfo());
                    break;
                } else {
                    wifiInfo = wifiInfoService.findRandomWifiInfo(wifiInfo);
                }
                i++;
            }
            if (StringUtils.isBlank(client.getWifiInfo())) {
                LOGGER.warn("wifiInfo is emtpy ,imsi [{}]", imsi);
                return false;
            }
            sb.append("wifiInfo,");
        }

        if (StringUtils.isBlank(client.getPhoneType())) {
            client.setPhoneType("1");
        }

        if (client.getNetworkType() == null) {
            client.setNetworkType(NetworkTypeEnum.WIFI.getType());
        }

        if (StringUtils.isBlank(client.getNetworkExtraInfo())) {
            client.setNetworkExtraInfo(WifiUtil.getWifiName());
        }

        if (StringUtils.isBlank(client.getAppName())) {
            client.setAppName(AppNameUtil.getAppName());
        }

        // 必填
        if (StringUtils.isBlank(client.getSystemAppName())) {
            if (mobileClient == null || StringUtils.isBlank(mobileClient.getSystemAppName())) {
                LOGGER.warn("SystemAppName is emtpy ,imsi [{}]", imsi);
                return false;
            }
            client.setSystemAppName(mobileClient.getSystemAppName());
        }
        // 必填
        if (StringUtils.isBlank(client.getProductDevice())) {
            if (mobileClient == null || StringUtils.isBlank(mobileClient.getProductDevice())) {
                LOGGER.warn("ProductDevice is emtpy ,imsi [{}]", imsi);
                return false;
            }
            client.setProductDevice(mobileClient.getProductDevice());
        }
        // 必填
        if (StringUtils.isBlank(client.getProductName())) {
            if (mobileClient == null || StringUtils.isBlank(mobileClient.getProductName())) {
                LOGGER.warn("ProductName is emtpy ,imsi [{}]", imsi);
                return false;
            }
            client.setProductName(mobileClient.getProductName());
        }
        // 必填
        if (StringUtils.isBlank(client.getDensity())) {
            if (mobileClient == null || StringUtils.isBlank(mobileClient.getDensity())) {
                LOGGER.warn("Density is emtpy ,imsi [{}]", imsi);
                return false;
            }
            client.setDensity(mobileClient.getDensity());

        }
        if (client.getDensityDpi() == null) {
            if (mobileClient != null && mobileClient.getDensityDpi() != null) {
                client.setDensityDpi(mobileClient.getDensityDpi());
            }
        }

        // 必填
        if (StringUtils.isBlank(client.getSdId())) {
            client.setSdId(Md5Utils.getMd5(imsi));
        }

        // 必填
        if (StringUtils.isBlank(client.getMac())) {
            String mac = initMac(imsi);
            if (mac != null) {
                client.setMac(mac);
            } else {
                LOGGER.warn("mac is emtpy ,imsi [{}]", imsi);
                return false;
            }
            sb.append("mac,");
        }

        // 必填
        if (StringUtils.isBlank(client.getAndroidId())) {
            String andriodId = initAndriodId(imsi);
            if (andriodId != null) {
                client.setAndroidId(andriodId);
            } else {
                LOGGER.warn("andriodId is emtpy ,imsi [{}]", imsi);
                return false;
            }
            sb.append("androidId,");
        }

        // 必填
        if (StringUtils.isBlank(client.getRelease())) {
            if (mobileClient == null || StringUtils.isBlank(mobileClient.getRelease())) {
                LOGGER.warn("Release is emtpy ,imsi [{}]", imsi);
                return false;
            }
            client.setRelease(mobileClient.getRelease());
        }
        // 必填
        if (StringUtils.isBlank(client.getBuildVersion())) {
            if (mobileClient == null || StringUtils.isBlank(mobileClient.getBuildVersion())) {
                LOGGER.warn("BuildVersion is emtpy ,hstype {} hsman {}", hstype, hsman);
                return false;
            } else {
                client.setBuildVersion(mobileClient.getBuildVersion());
            }
        }

        if (StringUtils.isBlank(client.getUserAgent())) {
            if (mobileClient != null && StringUtils.isNotBlank(mobileClient.getUserAgent())) {
                client.setUserAgent(mobileClient.getUserAgent());
            }
        }

        if (StringUtils.isBlank(client.getCpu())) {
            if (mobileClient != null && StringUtils.isNotBlank(mobileClient.getCpu())) {
                client.setCpu(mobileClient.getCpu());
            }
        }

        if (client.getXdpi() == null) {
            if (mobileClient != null && mobileClient.getXdpi() != null) {
                client.setXdpi(mobileClient.getXdpi());
            }
        }
        if (client.getYdpi() == null) {
            if (mobileClient != null && mobileClient.getYdpi() != null) {
                client.setYdpi(mobileClient.getYdpi());
            }
        }
        if (StringUtils.isBlank(client.getBoard())) {
            if (mobileClient != null && StringUtils.isNotBlank(mobileClient.getBoard())) {
                client.setBoard(mobileClient.getBoard());
            }
        }

        Short screenWidth = client.getScreenWidth();
        Short screenHeight = client.getScreenHeight();
        double xdpi = 0, ydpi = 0;
        Double xdpi1 = client.getXdpi();
        Double ydpi1 = client.getYdpi();
        if (xdpi1 != null) {
            xdpi = xdpi1;
        }
        if (ydpi1 != null) {
            ydpi = ydpi1;
        }

        BigDecimal y = new BigDecimal(ydpi);
        ydpi = y.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

        BigDecimal x = new BigDecimal(xdpi);
        xdpi = x.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

        if (screenWidth != null && screenHeight != null && screenWidth > screenHeight) {
            client.setScreenWidth(screenHeight);
            client.setScreenHeight(screenWidth);
            client.setXdpi(ydpi);
            client.setYdpi(xdpi);
        } else {
            client.setScreenWidth(screenWidth);
            client.setScreenHeight(screenHeight);
            client.setXdpi(xdpi);
            client.setYdpi(ydpi);
        }
        String fakeColumn = sb.toString();
        if (StringUtils.isNotBlank(fakeColumn)) {
            client.setFakeColumn(fakeColumn);
        }
        return true;
    }

    public UserClientInfo initUserClientinfo(HttpResult httpResult, IpRange ipRange) {
        UserClientInfo clientInfo = new UserClientInfo();
        Integer carrier = checkImsi(httpResult.getImsi());
        if (carrier != null && carrier != -1) {
            clientInfo.setCarrier(carrier);
        } else {
            return clientInfo;
        }
        clientInfo.setDensityDpi(httpResult.getDensityDpi());
        clientInfo.setProvince(ipRange.getProvinceId());
        clientInfo.setCity(ipRange.getCityId());
        clientInfo.setIp(httpResult.getIp());
        clientInfo.setBuildId(httpResult.getBuildId());
        if (!StringUtil.isBlank(httpResult.getLac())) {
            clientInfo.setLac(Integer.parseInt(httpResult.getLac()));
        }
        if (!StringUtil.isBlank(httpResult.getCellId())) {
            clientInfo.setCellId(Integer.parseInt(httpResult.getCellId()));
        }
        clientInfo.setLongitude(httpResult.getLongitude());
        clientInfo.setLatitude(httpResult.getLatitude());
        clientInfo.setSmsCenter(httpResult.getSmsCenter());
        clientInfo.setChannelId(httpResult.getChannelId());
        if (!StringUtil.isBlank(httpResult.getSdkVerCode())) {
            clientInfo.setSdkVersion(httpResult.getSdkVerCode());
        }
        clientInfo.setHsman(httpResult.getHsman());
        clientInfo.setHstype(httpResult.getHstype());
        clientInfo.setOsVer(httpResult.getOsVer());
        short width = 0, height = 0;
        String screenWidth = httpResult.getScreenWidth();
        String screenHeight = httpResult.getScreenHeight();
        if (!StringUtil.isBlank(screenWidth)) {
            width = Short.parseShort(screenWidth);
        }
        if (!StringUtil.isBlank(screenHeight)) {
            height = Short.parseShort(screenHeight);
        }
        double xdpi = 0, ydpi = 0;
        Double xdpi1 = httpResult.getXdpi();
        Double ydpi1 = httpResult.getYdpi();
        if (xdpi1 != null) {
            xdpi = xdpi1;
        }
        if (ydpi1 != null) {
            ydpi = ydpi1;
        }


        BigDecimal y = new BigDecimal(ydpi);
        ydpi = y.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

        BigDecimal x = new BigDecimal(xdpi);
        xdpi = x.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

        if (width > height) {
            clientInfo.setScreenWidth(height);
            clientInfo.setScreenHeight(width);
            clientInfo.setXdpi(ydpi);
            clientInfo.setYdpi(xdpi);
        } else {
            clientInfo.setScreenWidth(width);
            clientInfo.setScreenHeight(height);
            clientInfo.setXdpi(xdpi);
            clientInfo.setYdpi(ydpi);
        }
        clientInfo.setCpu(httpResult.getCpu());
        if (!StringUtil.isBlank(httpResult.getRamSize())) {
            clientInfo.setRamSize(Integer.parseInt(httpResult.getRamSize()));
        }
        if (!StringUtil.isBlank(httpResult.getRomSize())) {
            clientInfo.setRomSize(Integer.parseInt(httpResult.getRomSize()));
        }
        if (!StringUtil.isBlank(httpResult.getExtraSize())) {
            clientInfo.setExtraSize(Integer.parseInt(httpResult.getExtraSize()));
        }

        if (!StringUtil.isBlank(httpResult.getNetworkType())) {
            clientInfo.setNetworkType(Integer.parseInt(httpResult.getNetworkType()));
        }
        clientInfo.setImsi(httpResult.getImsi());

        String imei = checkOnlineAndGetImsiAndImei(httpResult.getImsi(), httpResult.getImei());
        if (StringUtils.isNotBlank(imei)) {
            clientInfo.setImei(imei);
        } else {
            clientInfo.setImei(initImei(httpResult.getImsi()));
        }
        clientInfo.setPhoneNum(httpResult.getPhoneNum());
        clientInfo.setMac(httpResult.getMac());
        clientInfo.setIccid(httpResult.getICCID());
        clientInfo.setSdId(httpResult.getSd_id());
        if (!StringUtil.isBlank(httpResult.getRoot())) {
            clientInfo.setRoot(Integer.parseInt(httpResult.getRoot()));
        }
        if (!StringUtil.isBlank(httpResult.getNetworkSystem())) {
            clientInfo.setNetworkSystem(Integer.parseInt(httpResult.getNetworkSystem()));
        }
        if (!StringUtil.isBlank(httpResult.getBuild_version())) {
            clientInfo.setBuildVersion(httpResult.getBuild_version());
        }

        if (!StringUtil.isBlank(httpResult.getOsVer())) {
            String[] osVers = httpResult.getOsVer().split("_");
            if (osVers.length == 1) {
                clientInfo.setRelease(osVers[0]);
            } else {
                clientInfo.setRelease(osVers[1]);
            }
        }
        clientInfo.setSerialno(httpResult.getSerialno());
        clientInfo.setPhoneType(httpResult.getNetworkSystem() + "");
        clientInfo.setAndroidId(httpResult.getAndroidId());
        clientInfo.setProductName(httpResult.getProductName());
        clientInfo.setProductDevice(httpResult.getProductDevice());
        clientInfo.setDensity(httpResult.getDensity());
        AppInfo appInfo = initClientAppName(httpResult.getAppInfo(), clientInfo.getHsman(), clientInfo.getHstype());
        clientInfo.setAppName(appInfo.getApp_name());
        clientInfo.setSystemAppName(appInfo.getSystem_app_name());
        clientInfo.setAppInfo(appInfo);
        clientInfo.setUserAgent(httpResult.getUserAgent());
        clientInfo.setBoard(httpResult.getBoard());
        clientInfo.setCpuSerial(httpResult.getCpuSerial());
        clientInfo.setKernelVer(httpResult.getKernelVersion());
        clientInfo.setNetworkExtraInfo(httpResult.getNetworkExtraInfo());
        clientInfo.setNetworkOperator(httpResult.getNetworkOperator());
        clientInfo.setNetworkOperatorName(httpResult.getNetworkOperatorName());
        clientInfo.setSimOperatorName(httpResult.getSimOperatorName());
        // 判断wifi信息是否为空，如果为空，则从数据库中获取wifi信息，否则直接用客户端的wifi信息
        String wifiInfo = httpResult.getReserved3();
        if (StringUtils.isBlank(wifiInfo)) {
            WifiInfo queryVo = new WifiInfo();
            queryVo.setIpCity(ipRange.getCityId());
            queryVo.setIpProvince(ipRange.getProvinceId());
            queryVo = wifiInfoService.findRandomWifiInfo(queryVo);
            if (queryVo == null) {
                LOGGER.warn("imsi cannot get wifi {}", httpResult.getImsi());
                return null;
            } else {
                wifiInfo = queryVo.getWifiInfo();
            }
        }
        if (StringUtils.isNotBlank(wifiInfo) && wifiInfo.length() > 1000) {
            wifiInfo = wifiInfo.substring(0, 1000);
            wifiInfo = wifiInfo.substring(0, wifiInfo.lastIndexOf("|"));
        }
        clientInfo.setWifiInfo(wifiInfo);
        clientInfo.setSdkUuid(httpResult.getUuid());
        clientInfo.setSensorInfo(httpResult.getSensorInfo());
        clientInfo.setRadioVersion(httpResult.getRadioVersion());
        return clientInfo;
    }


}

